package com.vitas.coin.ui.act;

import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.media3.common.MediaItem;
import androidx.media3.common.PlaybackException;
import androidx.media3.common.Player;
import androidx.media3.exoplayer.ExoPlayer;

import com.blankj.utilcode.util.BarUtils;
import com.huawei.hms.audioeditor.sdk.AudioExtractCallBack;
import com.huawei.hms.audioeditor.sdk.HAEAudioExpansion;
import com.snap.common.main.BaseAct;
import com.snap.util.ToastUtilKt;
import com.snap.util.edge.EdgePaddingMarginKt;
import com.vitas.coin.data.bean.ChildrenVoiceBean;
import com.vitas.coin.databinding.ActTakeBinding;
import com.vitas.coin.util.Audio;
import com.vitas.coin.util.Utils;

import java.io.File;

import kotlin.Unit;
import kotlin.jvm.functions.Function2;

public class TakeAct extends BaseAct {

    ActTakeBinding binding;
    ExoPlayer player;
    Handler h = new Handler();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActTakeBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        EdgePaddingMarginKt.paddingVerticalSystemWindowInsets(binding.getRoot());
        BarUtils.transparentStatusBar(this);
        BarUtils.setStatusBarLightMode(this, true);

        String s = getIntent().getStringExtra("path");
        setPlayer(s);

        binding.save.setOnClickListener(v -> download(s));
    }

    private void download(String path) {
        ChildrenVoiceBean bean = new ChildrenVoiceBean("video" + System.currentTimeMillis(), path);
        Utils.INSTANCE.download(this, bean, 3, new Function2<String, String, Unit>() {
            @Override
            public Unit invoke(String s, String s2) {
                h.post(() -> {
                    binding.take.setEnabled(true);
                    binding.take.setOnClickListener(v -> {
                        take(s2);
                    });
                });
                Log.e("tagg", "download return " + s + ", " + s2);
                return null;
            }
        }, null);
    }

    boolean done = false;

    private void take(String in) {
        done = false;
        Utils.INSTANCE.showLoadingDialog(this, "提取音频", new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                if (!done) {
                    HAEAudioExpansion.getInstance().cancelExtractAudio();
                }
            }
        });
        String exportPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC).getPath() + "/myStream";
        File f = new File(exportPath);
        f.mkdirs();
        String name = "a" + System.currentTimeMillis();
        Audio.export(this, in, exportPath, name, new AudioExtractCallBack() {
            @Override
            public void onSuccess(String s) {
                h.post(() -> {
                    ToastUtilKt.toast("提取完成");
                    done = true;
                    Utils.INSTANCE.dismissDialog();
                    binding.edit.setEnabled(true);
                    binding.set.setEnabled(true);
                    binding.edit.setOnClickListener(v -> {
                        if (Utils.INSTANCE.checkRight(TakeAct.this)) {
                            Audio.openEdit(TakeAct.this, s, name);
                        }
                    });
                    binding.set.setOnClickListener(v -> {
                        Utils.INSTANCE.setSound(TakeAct.this, new File(s), name);
                    });
                });
            }

            @Override
            public void onProgress(int i) {
                h.post(() -> Utils.INSTANCE.loadingProgress(i));
            }

            @Override
            public void onFail(int i) {
                h.post(() -> {
                    ToastUtilKt.toast("提取失败");
                    done = true;
                    binding.edit.setEnabled(false);
                    binding.set.setEnabled(false);
                    Utils.INSTANCE.dismissDialog();
                });
            }

            @Override
            public void onCancel() {
                h.post(() -> Utils.INSTANCE.dismissDialog());
            }
        });
    }

    private void setPlayer(String path) {
        player = new ExoPlayer.Builder(this).build();
        player.addListener(new Player.Listener() {
            @Override
            public void onPlayerError(PlaybackException error) {
                //播放异常
                ToastUtilKt.toast("无法播放该视频");
            }

            @Override
            public void onPlaybackStateChanged(int playbackState) {
                if (playbackState == Player.STATE_ENDED) {
                    ToastUtilKt.toast("播放完了");
                }
            }
        });
        binding.playerView.setPlayer(player);
        MediaItem item = MediaItem.fromUri(path);
        player.setMediaItem(item);
        player.prepare();
        player.setPlayWhenReady(true);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (player != null && player.isPlaying()) {
            player.pause();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        h.removeCallbacksAndMessages(null);
        if (player != null) {
            player.release();
        }
    }
}
